package org.kong.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.kong.mapper.RoleMapper;
import org.kong.pojo.dto.SysRoleDTO;
import org.kong.pojo.dto.SysRoleUpdateDTO;
import org.kong.pojo.entity.SysRole;
import org.kong.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * 加油
 *
 * @author konglingfeng
 * @date 2025/8/22
 * @desc
 */
@Slf4j
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<SysRole> list(SysRoleDTO sysRoleDTO) {

        List<SysRole> list = roleMapper.list(sysRoleDTO);


        return list;
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        roleMapper.delete(id);
        log.info("删除角色：{}", id);
        // 级联删除角色权限
        roleMapper.deleteRolePermissionByRoleId(id);
        log.info("删除角色权限：{}", id);
        // 级联删除角色用户
        roleMapper.deleteRoleUserByRoleId(id);
        log.info("删除角色用户：{}", id);
    }

    @Override
    @Transactional
    public void deleteBatch(List<Integer> ids) {
        roleMapper.deleteBatch(ids);
        log.info("删除角色：{}", ids);
        // 级联删除角色权限
        roleMapper.deleteRolePermissionByRoleIds(ids);
        log.info("删除角色权限：{}", ids);
        // 级联删除角色用户
        roleMapper.deleteRoleUserByRoleIds(ids);
        log.info("删除角色用户：{}", ids);
    }

    @Override
    public List<Integer> listByRoleId(Integer id) {
        return roleMapper.listByRoleId(id);
    }

    @Override
    @Transactional
    public boolean update(SysRoleUpdateDTO sysRoleUpdateDTO) {
        boolean flag = roleMapper.update(sysRoleUpdateDTO);
        roleMapper.deleteRolePermissionByRoleId(sysRoleUpdateDTO.getId());
        if (sysRoleUpdateDTO.getPermIds() != null) {
            roleMapper.addRolePermission(sysRoleUpdateDTO);
        }

        return flag;
    }

    @Override
    @Transactional
    public void add(SysRoleUpdateDTO sysRoleUpdateDTO) {
        roleMapper.add(sysRoleUpdateDTO);
        Integer id = roleMapper.selectByRoleName(sysRoleUpdateDTO.getRoleName());
        sysRoleUpdateDTO.setId(id);
        roleMapper.addRolePermission(sysRoleUpdateDTO);

    }
}
